package com.first.module.acm.dao.impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.first.core.dao.impl.BaseDaoImpl;
import com.first.module.acm.dao.AppRoleDao;
import com.first.module.acm.model.AppFunction;
import com.first.module.acm.model.AppRole;
import com.first.module.acm.model.FunUrl;

public class AppRoleDaoImpl extends BaseDaoImpl<AppRole>
    implements AppRoleDao
{

    public AppRoleDaoImpl()
    {
        super(AppRole.class);
    }

    public AppRole getByRoleName(String roleName)
    {
        String hql = "from AppRole ar where ar.roleName=?";
        return (AppRole)findUnique(hql, new Object[] {
            roleName
        });
    }

    public HashMap getSecurityDataSource()
    {
        final HashMap source = new HashMap();
        getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session)
                throws HibernateException, SQLException
            {
                String hql = "from AppRole";
                Query query = session.createQuery(hql);
                List roleList = query.list();
                AppRole role;
                TreeSet urlSet;
                for(Iterator iterator = roleList.iterator(); iterator.hasNext(); )
                {
                	
                    role = (AppRole)iterator.next();
                    urlSet = new TreeSet();
                    for(Iterator functions = role.getFunctions().iterator(); functions.hasNext();)
                    {
                        AppFunction fun = (AppFunction)functions.next();
                        for(Iterator urlIt = fun.getFunUrls().iterator(); urlIt.hasNext();) {
                        	urlSet.add(((FunUrl)urlIt.next()).getUrlPath());
                        }
                    }
                    source.put(role.getName(), urlSet);
                    

                }

                return source;
            }
        });
        return source;
    }
}
